package DataStructure_ZL.队列模拟.用队列模拟栈;

import java.util.LinkedList;
import java.util.Queue;

public class doubleQuery {
    private Queue<Integer> u1;
    private Queue<Integer> u2;

    //构造器
    public doubleQuery() {
        u1 = new LinkedList<>();
        u2 = new LinkedList<>();
    }

    //添加元素
    public void push(int x) {
        if (!u1.isEmpty()){
            u1.offer(x);
        }else if (!u2.isEmpty()){
            u2.offer(x);
        }else{
            u1.offer(x);
        }
    }

    //取元素
    public int pop() {
        if (empty()) return -1;
        if(!u1.isEmpty()){
            int size=u1.size();//提前取出大小因为后面大小会不断改变
            //将u1的元素添加到另外一个数列，留一个
            for (int i=0;i<size-1;i++){
                u2.offer(u1.poll());
            }
            return u1.poll();
        }else {
            int size=u2.size();
            for (int i=0;i<size-1;i++){
                u1.offer(u2.poll());
            }
            return u2.poll();
        }
    }

    //取顶部元素不删除
    public int top() {
        if (empty()) return -1;
        if(!u1.isEmpty()){
            int size=u1.size();//提前取出大小因为后面大小会不断改变
            //将u1的元素添加到另外一个数列，留一个
            for (int i=0;i<size-1;i++){
                u2.offer(u1.poll());
            }
            int x=u1.poll();
            u2.offer(x);
            return x;
        }else {
            int size=u2.size();
            for (int i=0;i<size-1;i++){
                u1.offer(u2.poll());
            }
            int x=u2.poll();
            u1.offer(x);
            return x;
        }
    }

    //判断是否为空
    public boolean empty() {
        return u1.isEmpty() && u2.isEmpty();
    }
}
